package com.pic.mgt.monitor.parser.syushin;

import java.text.ParseException;
import java.util.Date;

import com.pic.mgt.monitor.WrongUnitFormatException;
import com.pic.mgt.monitor.parser.TimeParser;
import com.pic.mgt.utils.DateConvertUtils;

public final class UploadTimeParser extends TimeParser {
	private int uploadTimeStartFromChar;
	private int uploadTimeEndToChar;
	
	// 執行時間字串格式
	private final String executionTimeStringFormat = "MMddHHmmss";

	@Override
	public Date parse(Object _confirmationFilename)
										throws WrongUnitFormatException  {
		String confirmationFilename = (String)_confirmationFilename;
		
		String uploadTimeString;
		try {
			// 從確認檔檔名取出上傳時間字串
			// throws StringIndexOutOfBoundsException
			uploadTimeString = confirmationFilename.
										substring(this.uploadTimeStartFromChar - 1,
												  this.uploadTimeEndToChar);
			
			// 確認格式是否正確
			// throws ParseException
			super.checkTimeString(uploadTimeString);
			
		} catch (StringIndexOutOfBoundsException e1) {
			throw new WrongUnitFormatException(
					"Confirmation filename format is invalid. Can't find upload time.", e1);
		} catch (ParseException e2) {
			throw new WrongUnitFormatException(
					"Confirmation filename format is invalid. Upload time is invalid.", e2);
		}
		
		Date uploadTime;
		try {
			uploadTime = DateConvertUtils.convertToDate(
					uploadTimeString, this.executionTimeStringFormat);
		} catch (StringIndexOutOfBoundsException e) {
			throw new WrongUnitFormatException(
					"Upload Time '" + uploadTimeString + "' is invalid.", e);
		} catch (NumberFormatException e) {
			throw new WrongUnitFormatException(
					"Upload Time '" + uploadTimeString + "' is invalid.", e);
		}		
		return uploadTime;
	}

	// --- getter and setter --- 
	
	public void setUploadTimeStartFromChar(int uploadTimeStartFromChar) {
		this.uploadTimeStartFromChar = uploadTimeStartFromChar;
	}

	public void setUploadTimeEndToChar(int uploadTimeEndToChar) {
		this.uploadTimeEndToChar = uploadTimeEndToChar;
	}
}
